package com.lineage.server.model.npc.action;

import com.lineage.server.utils.IterableElementList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class L1NpcXmlParser {
  private static final Map<String, Integer> _questIds = new HashMap<>();
  
  public static List<L1NpcAction> listActions(Element element) {
    List<L1NpcAction> result = new ArrayList<>();
    NodeList list = element.getChildNodes();
    Iterator<Element> iterator = (new IterableElementList(list)).iterator();
    while (iterator.hasNext()) {
      Element elem = iterator.next();
      L1NpcAction action = L1NpcActionFactory.newAction(elem);
      if (action != null)
        result.add(action); 
    } 
    return result;
  }
  
  public static Element getFirstChildElementByTagName(Element element, String tagName) {
    IterableElementList list = new IterableElementList(element.getElementsByTagName(tagName));
    Iterator<Element> iterator = list.iterator();
    if (iterator.hasNext()) {
      Element elem = iterator.next();
      return elem;
    } 
    return null;
  }
  
  public static int getIntAttribute(Element element, String name, int defaultValue) {
    int result = defaultValue;
    try {
      result = Integer.valueOf(element.getAttribute(name)).intValue();
    } catch (NumberFormatException numberFormatException) {}
    return result;
  }
  
  public static boolean getBoolAttribute(Element element, String name, boolean defaultValue) {
    boolean result = defaultValue;
    String value = element.getAttribute(name);
    if (!value.equals(""))
      result = Boolean.valueOf(value).booleanValue(); 
    return result;
  }
  
  public static int parseQuestId(String questId) {
    if (questId.equals(""))
      return -1; 
    Integer result = _questIds.get(questId.toLowerCase());
    if (result == null)
      throw new IllegalArgumentException(); 
    return result.intValue();
  }
  
  public static int parseQuestStep(String questStep) {
    if (questStep.equals(""))
      return -1; 
    if (questStep.equalsIgnoreCase("End"))
      return 255; 
    return Integer.parseInt(questStep);
  }
}
